import { createApp } from "vue"

import Cookies from "js-cookie"
import locale from "element-plus/dist/locale/zh-cn.mjs"
import "tailwindcss/tailwind.css"
import ElementPlus from "element-plus"
import "element-plus/dist/index.css"
import * as ElementPlusIconsVue from "@element-plus/icons-vue"
import VXETable from "vxe-table"
import "vxe-table/lib/style.css"
import "@/assets/styles/index.scss" // global css
// import "@/assets/iconfont/index.css";

import App from "./App"
import store from "./store"
import router from "./router"
// svg图标
import "virtual:svg-icons-register"
import SvgIcon from "@/components/SvgIcon"
// 全局组件
import Public from "@/componentsPublic"
import confirm from "@/plugins/confirm.jsx"
import DKVui from "dk-vui"
import "dk-vui/dist/style.css"
//挂在指令
import directive from "./directive/index.js"
import "@/plugins/vxe-table.js"
import { renderWithQiankun, qiankunWindow } from "vite-plugin-qiankun/dist/helper"
import { name as packageName } from "../package.json"

// 子应用修改项
import pinia from "@/store/index"
import keepAliveStore from "@/store/modules/keepalive"
const keepeStore = keepAliveStore(pinia)
import { useRouter } from "vue-router"

import action from "@/utils/action.js"
import { routes } from "@/router/index"
import tableFormApi from "@/api/tableForm"
let app
function render(props) {
  app = createApp(App)
  const { container, $parentRouter, routerEvent } = props
  // 主应用全局数据
  app.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange
  app.config.globalProperties.$setGlobalState = props.setGlobalState
  app.config.globalProperties.confirm = confirm
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }
  app.use(router)
  app.use(store)
  app.use(VXETable)
  app.use(Public)
  app.use(DKVui)
  DKVui.setup({
    keepStore: keepAliveStore,
    useRouter,
    table: {
      scrollHideForm: true,
      formConfig: {
        proxy: {
          mainKey: "id", // 主键
          query: async ({ model_type: scope }) => {
            let res = await tableFormApi.query({ scope })
            res.data?.forEach((item) => {
              item.name = item.title
              item.conditions = item.params
            })
            return res
          },
          // model_type 类型/ name 保存名称 / sc_id 主键 / conditions保存条件
          save: ({ model_type: scope, name: title, sc_id, conditions: params }) => tableFormApi.save({ scope, title, sc_id, params }),
          remove: ({ id }) => tableFormApi.remove(id),
        },
      },
    },
  })

  app.component("svg-icon", SvgIcon)
  app.use(directive)
  // 使用element-plus 并且设置全局的大小
  app.use(ElementPlus, {
    locale: locale,
    // 支持 large、default、small
    size: Cookies.get("size") || "default",
  })

  const c = container ? container.querySelector("#app") : document.getElementById("app")

  if (routerEvent) {
    // 如果首次跳转子页面就直接跳到父级页面
    let path = routes.find((item) => item.path === routerEvent.path)
    console.log("path" + path)
    // 页面路由跳转加上?mustJump=true  可以强制跳转子页面  暂未使用 后续自由扩展
    if (path && path.mate && path.meta.parentName && !(routerEvent && routerEvent.query && routerEvent.query.mustJump)) {
      let parent = routes.find((item) => item.name === path["meta"]["parentName"])
      $parentRouter.push(parent.path)
      keepeStore.pushKeepaliveList(parent.name)
      action.setGlobalState({
        changeMicoTabsPath: {
          to: {
            path: parent.path,
            fullPath: parent.path,
            query: {},
          },
          appName: "oms",
          type: "change",
        },
      })
      return
    } else {
      const newPath = routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, "/")
      const newFullPath = routerEvent.fullPath && routerEvent.fullPath.replace(/\/[^/]*\//, "/")
      router.push(newFullPath)
      let find = routes.find((item) => item.path === newPath)
      find && keepeStore.pushKeepaliveList(find.name)
    }

    requestAnimationFrame(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: "changeLoading",
          loading: false,
        },
      })
    })
  }
  app.mount(c)
}

renderWithQiankun({
  mount(props) {
    console.log(packageName + ": mount--子应用挂载", props)
    action.setActions(props)
    render(props)
  },
  bootstrap() {
    console.log(packageName + ": bootstrap")
  },
  async unmount(props) {
    await keepeStore.clearKeepaliveList()
    app.unmount()
    app._container.innerHTML = ""
    app = null
    console.error(packageName + ": unmount--销毁子应用")
  },
  update(props) {
    console.log(packageName + ": update", props)
    let { routerEvent } = props

    if (routerEvent) {
      const newPath = routerEvent.path?.replace(/\/[^/]*\//, "/")
      if (!newPath) return
      const hasId = ["/edit/", "/view/", "/create/", "/1688/"].find((d) => newPath.indexOf(d) > -1)
      let id = ""
      if (hasId) {
        id = newPath.slice(newPath.lastIndexOf("/") + 1)
      }
      switch (routerEvent.type) {
        case "push":
          {
            router.push({ ...routerEvent, path: newPath })
            const path = routes.find((item) => item.path.replace(":id", id) === newPath)
            path && keepeStore.pushKeepaliveList(path.name)
          }
          break
        case "replace":
          {
            router.replace({ ...routerEvent, path: newPath })
          }
          break
        case "close":
          {
            console.log("关闭缓存", newPath)
            const path = routes.find((item) => item.path.replace(":id", id) === newPath)
            path && keepeStore.closeKeepaliveList(path)
          }
          break
        case "visible":
          {
            console.warn("visible")
          }
          break
      }
    }
  },
})

// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({})
}
